<?php
namespace app\api\controller;
use think\Db;
use app\admin\model\Config;


//志愿服务 购买志愿卡和一对一
class ZhiyuanService extends App
{
    public function get_goods_list()
    {
        
		$map['is_show'] = 1;
		$list = Db::name("zhiyuan_goods")->where($map)->field('id,title,short_desc,price,price_yj')->order('sort asc,id asc')->select();  
		return $this->show(1,"success", $list);
		
    }
    
    public function get_goods_detail()
    {
        
        $id = $this->request->get("id",0,'intval'); 
        if(empty($id)){
            return $this->show(2001,"缺少id!", '');
        }
        $info = Db::name("zhiyuan_goods")->field('id,title,short_desc,desc,price,price_yj,info,questions,photo')->where('id',$id)->where('status',1)->find();
        if(empty($info)){
            return $this->show(2001,"数据不存在或已下架!", '');
        }
		
		$photos = explode(',',$info['photo']);
		$photos = array_filter($photos);
		foreach($photos as $kp=>$vp){ 
			//$photos[$kp] = config('app_host').$vp;
			$photos[$kp] = $vp;
		}
		$info['photo'] = $photos;
			
		return $this->show(1,"成功", $info);
		
    }
	
    //下单购买
    public function submit_order()
    {
        $user_id = $this->user_id;
        if($this->request->isPost()){
			//$data = $this->request->post();
			$data['course_id'] = $this->request->post("good_id",0);
			if( empty($data['course_id'])){
				return $this->show(2001,"缺少good_id", '');
			}
			$goods = Db::name("zhiyuan_goods")->where('id',$data['course_id'])->find();
			if(empty($goods)){
				return $this->show(2001,"服务不存在", '');
			}
			if($goods['price']<=0){
				return $this->show(2001,"免费服务无需购买", '');
			}
			Db::name("course_order")->where('course_id',$data['course_id'])->where('user_id',$user_id)->where('type',2)->where('status',1)->delete();
			$course_order = Db::name("course_order")->where('course_id',$data['course_id'])->where('user_id',$user_id)->where('type',2)->where('status',2)->find();
			if(!empty($course_order)){
				return $this->show(2001,"已经购买过了", '');
			}
			
			$data['user_id'] = $user_id;
			$data['order_sn'] = $this->build_order_no();//生成唯一订单号
			$data['order_money'] = $goods['price'];
			$data['course_title'] = $goods['title'];
			$data['status'] = 1;
			$data['type'] = 2;
			$data['create_time'] = time();
			Db::startTrans();
			$flag = Db::name("course_order")->strict(false)->insertGetId($data);
				
			if($flag){
				$data_return = ['order_id'=>$flag,'order_sn'=>$data['order_sn']];
				Db::commit();
				return $this->show(1,"success", $data_return);
			}else{
				Db::rollback();
				return $this->show(2002, "fail", "");
			}
		}else{
            return $this->show(2001,"非法请求", '');
        }	
    }
}